/*
 * Project Name spring-boot-tools
 * File Name MessageHandler
 * Package Name com.huxiaosu.tools.mina.action
 * Create Time 2024/5/25
 * Create by name：liujie
 */
package com.huxiaosu.tools.mina.action;

import com.huxiaosu.tools.mina.cache.SessionUsers;
import com.huxiaosu.tools.mina.model.BaseMessage;
import com.huxiaosu.tools.mina.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 * Description
 *
 * @author liujie
 * @date 2024/5/25 14:05
 */
@Slf4j
public class MessageHandler extends IoHandlerAdapter {
    @Override
    public void sessionCreated(IoSession session) throws Exception {
        log.debug("<sessionId = [{}] created> ", session.getId());
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        log.debug("sessionOpened()...sessionId=" + session.getId());
        log.debug("<sessionId = [{}] created> ", session.getId());
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        log.debug("<sessionId = [{}] closed > ", session.getId());
        SessionUsers.getInstance().clearSession(session.getId());
        session.closeNow();
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        log.info("<sessionIdle sessionId = [{}] ,status = [{}] >",session.getId(),status);
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        log.info("<messageSend sessionId = [{}] ,message = [{}]>",session.getId(),message);
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        log.info("< exceptionCaught {} >" , cause.getMessage());
        session.closeNow();
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        log.info("< messageReceived = {}>", ToStringBuilder.reflectionToString(message));
        BaseMessage baseMessage = new BaseMessage();
        try {
            baseMessage = (BaseMessage) message;
        } catch (Exception e) {
            baseMessage.setType(Constants.T101);
        }

        MessageActionPool.getInstance().getAction(baseMessage.getType()).executeAction(session, baseMessage);
    }
}
